package yeh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import yeh.domain.LoginLog;
import yeh.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/login")
    public String login(HttpServletRequest request,Model model) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
//
        System.out.println("username:"+username);
        System.out.println("password:"+password);

        System.out.println(userService.Login(username, password));
        if (userService.Login(username, password)!=null) {
            // 登录成功-存入数据用于前端读写
            request.getSession().setAttribute("username", username);
            //读取登录日志返回给前端
            List<LoginLog> loginLogs = userService.getLoginfo();
            model.addAttribute("loginLogs", loginLogs);
            //跳转
            return "main.jsp";
        } else {
            // 登录失败，重新跳转到登录页面
            return "redirect:login.jsp";
        }
    }
}
